#include "stdafx.h"
#include <windows.h>

#include "GPGMEExt.h"

/*
typedef struct tagPROCESSENTRY32 {
DWORD     dwSize;
DWORD     cntUsage;
DWORD     th32ProcessID;
ULONG_PTR th32DefaultHeapID;
DWORD     th32ModuleID;
DWORD     cntThreads;
DWORD     th32ParentProcessID;
LONG      pcPriClassBase;
DWORD     dwFlags;
TCHAR     szExeFile[MAX_PATH];
} PROCESSENTRY32, *PPROCESSENTRY32;
*/

BOOL KillProcessByID(DWORD ProcessId)
{
	HANDLE hProcess = OpenProcess(
		PROCESS_TERMINATE,
		FALSE,
		ProcessId);

	if(hProcess == NULL)
	{
		//Fail
		return FALSE;
	}
	else if(TerminateProcess(hProcess,0))
	{
		//Success
		return TRUE;
	}
	else
	{
		//Fail
		return FALSE;
	}
}

BOOL KillProcessByID(PROCESSENTRY32& pid)
{
	return KillProcessByID(pid.th32ProcessID);
}

PID_LIST* FindMyChildProcessIDs()
{
	DWORD curPid = GetCurrentProcessId();
	return FindChildProcessIDs(curPid);
}

PID_LIST* FindChildProcessIDs(DWORD curPID)
{
	PID_LIST* pid_list = NULL;
	PROCESSENTRY32  pe32;
	pe32.dwSize = sizeof(pe32);

	HANDLE          hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	BOOL            bMore = Process32First(hProcessSnap, &pe32);

	//Check snapshot status.
	if (hProcessSnap == INVALID_HANDLE_VALUE)
	{
		OutputDebugString("CreateToolhelp32Snapshot Fail!\n");
		return NULL;
	}

	//Save match item
	pid_list    = new PID_LIST;

	while (bMore)
	{
		if (pe32.th32ParentProcessID == curPID)
		{
			pid_list->push_back(pe32);
		}
		bMore = Process32Next(hProcessSnap, &pe32);
	}

	//Check whether have one item at least.
	if (pid_list->size() == 0)
	{
		delete pid_list;
		pid_list = NULL;
	}

	//Close snapshot.
	CloseHandle(hProcessSnap);

	return pid_list;
}
